/*
             LUFA Library
     Copyright (C) Dean Camera, 2010.
              
  dean [at] fourwalledcubicle [dot] com
      www.fourwalledcubicle.com
*/

/*
  Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
    Additional LoopBack demo code by Opendous Inc. 2010-03-03
    For more info visit: www.Micropendous.org/LoopBack

  This firmware enumerates as a vendor-class device meaning
  the developer must decide and code a communication scheme.
  Examples of arbitrary endpoint as well as control endpoint
  communication are given.
  Search for TODO statements for implementation hints.
  Avoid busy loops as the USB task is not preemptive and USB
  has timing contraints.  Use concurrent programming techniques.
  For example, have one function set a flag when an event occurs.
  Have another function do significant processing only if the flag is set.
  Have both functions run from main()'s for(;;) loop, which should be the
  only indefinite loop in your firmware.

  Permission to use, copy, modify, and distribute this software
  and its documentation for any purpose and without fee is hereby
  granted, provided that the above copyright notice appear in all
  copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

#include "usbtointerface.h"

volatile uint8_t dataToSend[DATA_OUT_EPSIZE];
volatile uint8_t dataReceived[DATA_IN_EPSIZE];

int main(void)
{
	SetupHardware();
	

	sei();

        
        

         
	for (;;)
	{
            
		USB_USBTask();
                Kernschmiede_Task();
                
	}
}

void SetupHardware(void)
{
	
	/* Disable watchdog if enabled by bootloader/fuses */
	MCUSR &= ~(1 << WDRF);
	wdt_disable();

	/* Disable clock division */
	clock_prescale_set(clock_div_1);
	#if ((defined(__AVR_AT90USB1287__) || defined(__AVR_AT90USB647__) ||  \
			defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB646__) ||  \
			defined(__AVR_ATmega16U4__)  || defined(__AVR_ATmega32U4__) ||  \
			defined(__AVR_ATmega32U6__)))
		// note the JTD bit must be written twice within 4 clock cycles to disable JTAG
		// you must also set the IVSEL bit at the same time, which requires IVCE to be set first
		// port pull-up resistors are enabled - PUD(Pull Up Disable) = 0
		MCUCR = (1 << JTD) | (1 << IVCE) | (0 << PUD);
		MCUCR = (1 << JTD) | (0 << IVSEL) | (0 << IVCE) | (0 << PUD);
	#endif
        
	USB_Init();
        INIT_leds();
	
       
}

/** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
 *  starts the library USB task to begin the enumeration and USB management process.
 */
void EVENT_USB_Device_Connect(void)
{
	/* Indicate USB enumerating */
        LED2_on();
}

/** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
 *  of the USB device after enumeration, and configures the device endpoints.
 */
void EVENT_USB_Device_ConfigurationChanged(void)
{	
	/* Indicate USB connected and ready */
	
	/* Setup SendDataToHost Endpoint */
	if (!(Endpoint_ConfigureEndpoint(DATA_OUT_EPADDR, EP_TYPE_BULK,
					EPSIZE,
					 1)))
	{
		LED2_on();
	}
	
	/* Setup ReceiveDataFromHost Endpoint */
	if (!(Endpoint_ConfigureEndpoint(DATA_OUT_EPADDR, EP_TYPE_BULK,
					EPSIZE,
					1)))
	{
		LED2_on();
	}

}

void Kernschmiede_Task(void)
{
	/* Device must be connected and configured for the task to run */
	if (USB_DeviceState != DEVICE_STATE_Configured){
            return; 
        }

        ReceiveDataFromHost();
        


       
      
       
}

/*
void EVENT_USB_Device_UnhandledControlRequest(void)
{

	// TODO - Control Endpoint communication.  Just match up bRequest and bmRequestType values
	//			in your corresponding USB software to send and/or receive data.
	//

	switch (USB_ControlRequest.bRequest)
	{
		case 1:
			if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_VENDOR |  \
                                                                 REQTYPE_STANDARD))
			{
				// Send data to the host
				// Acknowledge the SETUP packet, ready for data transfer
				Endpoint_ClearSETUP();

				// Write data to the control endpoint
                                
				Endpoint_Write_Control_Stream_LE(&dataToSend, sizeof(dataToSend));

				// Finalize the stream transfer to send the last packet or clear the host abort
				Endpoint_ClearOUT();
			}

			break;

		case 2:
			if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_VENDOR |  \
                                                                 REQTYPE_STANDARD))
			{
				// Receive data from the host
				// Acknowledge the SETUP packet, ready for data transfer
				Endpoint_ClearSETUP();

				// Read data in from the host
                                //LED1_t();
				//Endpoint_Read_Control_Stream_LE(&dataReceived, sizeof(dataToSend));

				// Finalize the stream transfer to clear the last packet from the host
				Endpoint_ClearIN();
			}

			break;

	}
}
*/

void ReceiveDataFromHost(void)
{
  Endpoint_SelectEndpoint(DATA_OUT_EPADDR);
  if(Endpoint_IsOUTReceived())
  {
     if(Endpoint_IsReadWriteAllowed())
     {
     
        Endpoint_Read_Stream_LE(&dataReceived, sizeof(dataReceived),NULL);
        switch(dataReceived[0])
        {
           case 'a':
             LED1_t();
             break;
           case 'b':
             LED3_t();
        }
     }
     
  }
  Endpoint_ClearOUT();

}




